import axios from 'axios'
import store from '../store/index'
import router from '../router/index'
import options from './option'
const service = axios.create({
  baseURL: options.baseURL,
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer ' + store.state.user.token,
    'X-Requested-With': 'XMLHttpRequest'
  }
})

service.interceptors.request.use(
  function (config) {
    if (store.state.user.token) {
      // config.headers.token = 'Bearer ' + store.state.user.token
      config.headers.Authorization = 'Bearer ' + store.state.user.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  function (response) {
    const dataAxios = response.data
    return dataAxios
  },
  function (error) {
    if (error.message === 'Request failed with status code 401') {
      if (router.currentRoute.name !== 'login') {
        router.push('/login')
      }
      store.dispatch('user/removeToken')
      // console.log('身份信息已过期，重新登录', error)
      return {
        msg: 'token expire'
      }
    }
    // 防止后端挂掉前端乱成一锅粥
    if (error.code === 'ERR_BAD_REQUEST' && router.currentRoute.name !== 'login' && router.currentRoute.name !== 'error') {
      router.push('/error')
    }
  }
)

export default service
